<template>
	<view style="width: 100vw;height: 100vh;" class="bg-white">
		<!-- 顶部按钮 -->
		<view class="cu-custom" :style="[{height:CustomBar + 'px'}]">
			<view class="cu-bar fixed flex justify-between align-center" :style="{height:CustomBar+'px',paddingTop:StatusBar+'px'}" style="font-size: 32rpx;" >
				<text class=" cuIcon-back margin-left" @click="back" style="font-size: 40rpx;"></text>
				<text class=" text-blue margin-right" @click="send()">发布</text>
			</view>
		</view>
		<view style="margin-top: 24rpx; padding: 0 32rpx; line-height: 64rpx;">
			<textarea v-model="article.title" style="color: #131415;font-size: 40rpx;font-weight: bold;" auto-height
				placeholder="请输入标题（5-30个字）" maxlength="30" placeholder-style="font-size: 40rpx;color: #999999;" />
		</view>
		<view class="solid-bottom" style="height: 20rpx;"></view>
		<view style="margin-top: 24rpx; padding: 0 32rpx; ">
			<uni-file-picker :value="value" fileMediatype="image" mode="grid" limit="3" :auto-upload="false" @select="select" 
				@delete="deleteCover" title="最多选择3张封面图" :image-styles="{height:'200rpx', width: '200rpx'}">
			</uni-file-picker>
		</view>
		
		<view class="cu-form-group" >
			<view class="title">标签选择</view>
			<view class="picker" @click="openSelect">
				请选择<text class="cuIcon-right"></text>
			</view>
		</view>
	    <!-- 多列选择器 -->	
		<tki-tree ref="tree" :range="range" rangeKey="title" :multiple="true" @confirm="confirm" confirmColor="#4e8af7" />
		<!-- 富文本编辑器 -->
		<jinEdit placeholder="请输入正文" @editOk="editOk" :uploadFileUrl="uploadUrl" :html="html"
			ref="jinEdit"></jinEdit>
	</view>
</template>

<script>
	import tkiTree from "../../components/tki-tree/tki-tree.vue"
	import jinEdit from '../../components/jin-edit/jin-edit.vue'
	export default {
		data() {
			return {
				range:[],//多选				
				value:[],//文件上传组件数据回显
				html:"",//富文本数据回显
				uploadUrl: "http://xuewenbao.cn:38880/xwb/edu/file/uploadOSS",
				covers: [],
				article: {
					"content": "",
					"cover": "",
					"status": "",
					"title": "",
					"userId": "",
					"subjectList":[]
				},
				coversInfo:[],//存放封面信息数组，供删除使用
			}
		},
		components: {
			jinEdit,
			tkiTree
		},
		onLoad(){
			//获取分类	
		    this.getSubject().then(res =>{
				 Promise.all(this.getChildSubject(res)).then(res2 =>{
					 this.range=res2
				 })
				})
			//获取草稿箱
			if(JSON.stringify(this.$Route.query)=='{}'){
				return;
			}
			//根据草稿箱进行渲染
			if(this.$Route.query.draft.cover){
			let obj ={
				url:this.$Route.query.draft.cover
			}
			this.value.push(obj)
			this.covers.push(obj.url)
			}
			if(this.$Route.query.draft.title){
				this.article.title=this.$Route.query.draft.title
			}
			if(this.$Route.query.draft.content){
				this.html=this.$Route.query.draft.content
			}
		},
		methods: {
			confirm(e){
				e.forEach(item =>{
					this.article.subjectList.push(item.id)
				})
			},
			openSelect(){
				this.$refs.tree._show()
			},
			//获取一级分类
			getSubject(){
				return new Promise((resolve,reject)=>{
					this.$http.get('/edu/onesubject/getAllOneSubject').then(res =>{
					resolve(res.data.result)
				})
				})
			},
			//获取子分类,获取二级分类num传0，获取三级分类num传1
			getChildSubject(array){
				let proArray=[];
				for(let i=0;i<array.length;i++){
					proArray.push(new Promise((resolve,reject)=>{
					 this.$http.get('/edu/child-subject/getAllChildSubject/'+array[i].id).then(res =>{
						 let {result}=res.data
						 result.forEach(val=>{
						 val.children=val.subjectVoList
						 delete val.subjectVoList
						 })
						 array[i].children=result
						 resolve(array[i])
					})
				}))
				}
				return proArray;
			},
			async select(e) {
				console.log('选择文件：', e);
				uni.showLoading({
					title: '正在上传中...'
				})
				for (let temp of e.tempFiles) {
					// 图片上传服务器
					console.log(temp.path)
					await uni.uploadFile({
						url: this.uploadUrl,
						filePath: temp.path,
						name: "file",
						formData: {
							'biz': 'cover'
						},
						success: res => {
							// 上传完成后处理
							let data = JSON.parse(res.data)
							console.log(data)
							if (data.success) {
								this.covers.push(data.message)
								let obj={
									url:data.message,
									cloudPath:e.tempFiles[0].cloudPath
								}
								this.coversInfo.push(obj)
								console.log(this.coversInfo)
							} else {
								console.log("cover上传失败", data.message)
							}
							uni.hideLoading()
						},

					});
				}
			},
			deleteCover(e) {
				uni.showLoading({
					title:'删除中...'
				})
				let url=null
				this.coversInfo.forEach(item =>{
					if(item.cloudPath==e.tempFile.cloudPath){
						url=item.url
					}
				})
				if(url){
					this.$http.post('/edu/file/deleteOss',url).then(res =>{
						if(res.data.success){
							uni.hideLoading()
							this.$tip.success('删除成功')
							this.covers.forEach((item,index) =>{
								if(item==url){
									this.covers.splice(index,1)
								}
							})
						}
					})
				}
			},
			back() {
				this.$tip.confirm("是否存入草稿箱？", true).then(() => {
					this.$refs.jinEdit.release();
					this.upLoad(false);
				}, () => {
					uni.navigateBack({
						delta: 1
					})
				});
			},
			send() {
				this.$refs.jinEdit.release();
				this.upLoad(true);
			},
			editOk(res) {
				console.log(res.html)
				this.article.content = res.html;						
			},
			upLoad(isPublish) {
				if(!this.article.content){
					return;
				}
				if(isPublish){
					this.article.userId = this.$store.getters.userid;
					this.article.cover = this.covers.join(',');
					this.article.status = 'Normal';
					console.log(this.article)
					this.$http.post("/edu/article/addArticle", this.article).then(res=>{
						if(res.statusCode === 200) {
							this.$tip.success('文章发表成功!');
							this.$Router.replaceAll({name: 'createCenter'})
						}else {
							this.$tip.error('文章发表失败!');
						}
					})
				}else {
					this.article.userId = this.$store.getters.userid;
					this.article.cover =this.covers.length>0? this.covers.join(','):"";
					this.article.status = 'Draft';
					this.$http.post("/edu/article/addArticle", this.article).then(res=>{
						if(res.statusCode === 200) {
							this.$tip.success('草稿保存成功!');
							this.$Router.replaceAll({name: 'createCenter'})
						}else {
							this.$tip.error('草稿保存失败!');
						}
					})
				}
			},
      }
	}
</script>

<style>
</style>
